package com.developer.platform.domain.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.developer.platform.domain.Log;
import com.developer.platform.domain.User;
import com.developer.platform.domain.repository.IUserRepository;
import com.developer.platform.infrastructure.data.mapper.LogMapper;
import com.developer.platform.infrastructure.enums.StatusEnum;
import com.google.common.eventbus.Subscribe;
import com.veeker.log.event.SystemErrorLogEvent;
import com.veeker.log.event.SystemLogEventPublisher;
import com.veeker.log.event.SystemSuccessLogEvent;
import java.util.Objects;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2021-01-07
 */
@Component
public class SystemLogEventListener {

  private final LogMapper logMapper;
  private final IUserRepository userRepository;

  public SystemLogEventListener(SystemLogEventPublisher systemLogEventPublisher,
      LogMapper logMapper,
      IUserRepository userRepository) {
    this.logMapper = logMapper;
    this.userRepository = userRepository;
    systemLogEventPublisher.register(this);
  }

  @Subscribe
  public void asyncPublishSystemErrorLogEvent(SystemErrorLogEvent systemLogEvent){
    Log log = new Log(Long.parseLong(systemLogEvent.getCurrUserId()), StatusEnum.N,
        systemLogEvent.getErrorTime(), systemLogEvent.getErrorCountent());
    BeanUtil.copyProperties(systemLogEvent, log);
    this.loginUserId(log);
    logMapper.insert(log);
  }

  @Subscribe
  public void asyncPublishSystemSuccessLogEvent(SystemSuccessLogEvent systemLogEvent){
    Log log = new Log(Long.parseLong(systemLogEvent.getCurrUserId()), StatusEnum.Y);
    BeanUtil.copyProperties(systemLogEvent, log);
    this.loginUserId(log);
    logMapper.insert(log);
  }

  public void loginUserId(Log log){
    if("登录".equals(log.getDiscription())){
      User byUsername = userRepository.findByUsername(
          JSONUtil.parseObj(JSONUtil.parseObj(log.getInputParam()).getStr("login")).getStr("principal"));
      if(Objects.nonNull(byUsername)){
        log.setCreateBy(byUsername.getId());
      }
    }
  }

}
